#!/usr/bin/python3
#coding=utf-8

import remi.gui as gui
import PySimpleGUI as sg

from remi import start, App
from remi.server import App, start, Server
from threading import Timer
import time


from customer import *
from systemList import *
from productLine import *
from systemVersionNum import *
from userInfo import *

from loadParam import *

g_log=CLog("../logs/shengli_oa_test_support_" + datetime.datetime.now().strftime('%Y%m%d') + ".log", True)
g_userInfoMgr = CUserInfoMgr(log=g_log)
g_sysTemListMgr = CSysTemListMgr(log=g_log)
g_customerMgr = CCustomerMgr(log=g_log)
g_productLineMgr = CProductLineMgr(log=g_log)


class CWebService(App):
    firstMenuList = ["主菜单", "客户信息", "系统类型", "产品线", "版本管理", "FPGA分类", "网卡分类", "生产机房"]
    endMenuList = ["工作登记", "出厂记录", "上线记录", "变更记录", "升级记录", "版本回退", "机器替换", "生产事故", "操作日志"]
    rightOper = ["操作项", "修改", "新增", "删除", "刷新"]
    systemList = []
    productSysDict = {}
    productSysTable = {}
    logonStatus = False
    inputText = ""
    def __init__(self, *args):
        super(CWebService, self).__init__(*args)
        g_log.log("connection established " + str(self.client_address))




    # 记录时间
    def idea(self):
       self.progress.set_value(value=1)

    def on_img_clicked(self):
        return self.getMainSheet()

    def list_view_on_selected(self, widget, selected_item_key):
        table=gui.TableRow
        systemList = self.systemList[selected_item_key]
        for id in range(1, len(systemList)):
            sysRow = gui.TableRow(systemList[id])
            sysRow.on_row_item_click.do(self.on_sys_info_mod)
            table.append(sysRow)

        return self.addSubViews(self.getFirstMenu(), self.getSubContainerLeft(), table,
                                self.getSubContainerRight(), self.getEndMenuLine(), window=self.getMainView())


    def on_sys_info_mod(self):
        pass

    def on_button_pressed(self, param = ""):
        if(param == "canel logon"):
            pass

        if (param == "add"):
            pass

        if (param == "mo"):
            pass

        if (param == "del"):
            # 弹框
            sg.popup_yes_no("确认删除该条数据？(yes/no)", no_titlebar=True, keep_on_top=True)


    def on_text_area_change(self, text):
        self.inputText = text.get_text()

    def on_main_menu_press(self):
        return self.getMainSheet()

    def on_menu_press(self, param):
        msgType = param.get_text()
        if(msgType=="客户信息"):
            sg.popup(CustomerType,title="",line_width=100, text_color="black",background_color="white",
                     no_titlebar=False, keep_on_top=True, custom_text="  ok  ")
            if self.logonStatus is False:
                sg.popup("请先登录", no_titlebar=True, keep_on_top=True)
                return
            customer=sg.popup_get_text("客户名称")
            type=sg.popup_get_text("客户类别:期货公司;券商;私募")
            g_customerMgr.add(self.userinfo.user, customerName=customer, customerType=type)
            g_customerMgr.reload()
        if (msgType=="产品线"):
            sg.popup(ProductType,title="",line_width=100, text_color="black",background_color="white",
                     no_titlebar=False, keep_on_top=True, custom_text="  ok  ")
        if (msgType == "板卡分类"):
            sg.popup(FPGAType,title="",line_width=100, text_color="black",background_color="white",
                     no_titlebar=False, keep_on_top=True, custom_text="  ok  ")
        if (msgType == "网卡分类"):
            sg.popup(NetCardType, title="",line_width=100, text_color="black",background_color="white",
                     no_titlebar=False, keep_on_top=True, custom_text="  ok  ")
        if (msgType == "生产机房"):
            sg.popup(ExchangeRoom, title="",line_width=100, text_color="black",background_color="white",
                     no_titlebar=False, keep_on_top=True, custom_text="  ok  ")
        if(msgType=="你好,请登录"):
            return self.addSubViews(self.getFirstMenu(), self.getlogonView(), window=self.getMainView())

    def on_logon_click(self):
        userList = g_userInfoMgr.userInfo
        if userList[self.userinfo.user].pwd != self.userinfo.pwd:
            # 密码错误
            sg.popup("用户名密码错误!")
            return

        if userList[self.userinfo.user].pwd == self.userinfo.pwd:
            if(self.userinfo.pwd == getPwd("000000")):
                # 第一次登录
                newPwd=sg.popup_get_text("请输入密码:")
                if newPwd == "000000":
                    sg.popup("密码无效!")
                elif newPwd=="":
                    sg.popup("密码为空!")
                else:
                    self.logonStatus=True
                    self.userinfo.pwd=getPwd(newPwd)
                    g_userInfoMgr.updateUserPwd(user=self.userinfo.user, newPwd=self.userinfo.pwd)


                return self.getMainSheet()
            else:
                # 登录成功
                self.logonStatus = True
                return self.getMainSheet()

    def getlogonView(self):
        #sg.popup("请登录")
        logonView = gui.Container(width=320, style={'display': 'block', 'overflow': 'auto', 'text-align': 'center'})
        logonView.append(gui.Label("用户名:", width=200, height=30, margin='10px'))
        logonView.append(gui.Label("密  码:", width=200, height=30, margin='10px'))
        logonName = gui.TextInput(width=200, height=30, margin='10px')
        logonName.onchange.do(self.on_text_area_change)
        self.pwd = gui.TextInput(width=200, height=30, margin='10px')
        self.pwd.onchange.do(self.on_text_area_change)

        logonButton = gui.Button("登录", width=200, height=30, margin='10px')
        canclButton = gui.Button("取消", width=200, height=30, margin='10px')
        logonButton.onclick.do(self.on_logon_click)
        canclButton.onclick.do(self.on_button_pressed(param= "canel logon"))

        logonView.append(logonName)
        logonView.append(self.pwd)
        logonView.append(logonButton)
        logonView.append(canclButton)
        return logonView

    def getMainView(self):
        globalContainer=gui.Container(width=2100, margin='0px auto',
                      style={'display': 'block', 'overflow': 'hidden'})
        return globalContainer

    def getFirstMenu(self):
        firstMenuLine = gui.Menu(width="100%", height=30,style={"background":"blue"})

        mainMenu =  gui.MenuItem("主页", width="15%",height=30)
        mainMenu.onclick.do(self.on_main_menu_press)
        menuitems = [mainMenu]
        for id in range(1, len(self.firstMenuList)):
            menuItem = gui.MenuItem(self.firstMenuList[id], width="5%",height=30)
            menuItem.onclick.do(self.on_menu_press)
            menuitems.append(menuItem)

        buttonText = "你好,请登录"
        if (self.logonStatus is True):
            buttonText = "你好," + self.userinfo.user + "!"
        menuitems.append(gui.MenuItem(" ",width="30%",height=30))
        logonMenuItem = gui.MenuItem(buttonText,width="20%",height=30)
        logonMenuItem.onclick.do(self.on_menu_press)
        menuitems.append(logonMenuItem)

        firstMenuLine.append(menuitems)
        menubar = gui.MenuBar(width=1800, height=30)
        menubar.append(firstMenuLine)
        return menubar

    def getSubContainerLeft(self):
        container = gui.Container(width=100, margin='0px auto', style={'display': 'block', 'overflow': 'hidden'})
        products = g_productLineMgr.productLine

        productsRetList = gui.ListView.new_from_list(products, width="20%", height=1800, margin='10px')
        productsRetList.onselection.do(self.list_view_on_selected)
        self.systemList = g_sysTemListMgr.systemList

        # 字段名
        key = "系统类型"
        # 初始假数据
        self.productSysDict[key]=self.systemList

        # 先按产品类别分类，每个产品类别下挂系统列表
        for id in range(1, len(self.systemList)):
            productType = self.systemList[id][g_sysTemListMgr.getIndexByName(key)]
            if productType in products:
                self.productSysDict[productType].append(self.systemList[id])

        container.append(productsRetList)
        return container

    def getSubContainerCenter(self):
        container = gui.Container(width=1500, margin='0px auto', style={'display': 'block', 'overflow': 'hidden'})
        table = gui.Table.new_from_list(self.systemList, width=1500)
        container.append(table)
        return container


    def getSubContainerRight(self):
        container = gui.Container(width=100, margin='0px auto', style={'display': 'block', 'overflow': 'hidden'})
        rightMenu = gui.Menu("", width= "10%", height=1800, margin="10px", style={"background":"white"})
        container.append(rightMenu)
        return container


    def getEndMenuLine(self):
        container = gui.Container(width=1800, margin='0px auto', style={'display': 'block', 'overflow': 'hidden','color':'white'})
        for i in range(1, len(self.endMenuList)):
            botton = gui.Button(self.endMenuList[i],width=100,background_color="white")
            botton.onclick.do(self.on_button_pressed)
            container.append(botton)
        return container

    def onEndMenuClick(self):
        pass

    def on_table_row_click(self, row, item):
        if len(row) == 0 or item is None:
            return

        id = row[0]
        changeRow = []
        # 需要更新的字段 all
        updateFields = {"编号": id}
        for index in range(1, len(row)):
            text = gui.TextInput(row[index])
            text.onchange.do(self.on_text_area_change)
            text.set_text(self.inputText)
            changeRow.append(text)

        ###
        sysList = self.productSysDict[0]

        for index in range(1, len(item)):
            text = gui.TextInput(width=item[index].len)
            text.set_text(item[index].text)
            text.onchange.do(self.on_text_area_change)
            text.set_text(self.inputText)

    def getMainSheet(self):
        verticalContainer = self.getMainView()

        # 导航栏
        firstMenuLine = self.getFirstMenu()
        # 左侧栏
        subContainerLeft = self.getSubContainerLeft()
        # 主窗
        subContainerCenter = self.getSubContainerCenter()
        # 右侧栏
        subContainerRight = self.getSubContainerRight()
        # 底栏
        endMenuLine = self.getEndMenuLine()


        return self.addSubViews(firstMenuLine, subContainerLeft, subContainerCenter,
                                subContainerRight, endMenuLine, window=verticalContainer)

    def main(self):
        self.userinfo = UserInfo(user="")
        self.logonStatus = False
        self.progress = gui.Progress(1, 100, width=200, height=5)
        return self.getMainSheet()




    @staticmethod
    def timeNow():
        return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

    @staticmethod
    def dropDownAddAccounts(*accountList, dropDown):
        [dropDown.append(gui.DropDownItem(text=element), element) for element in accountList]

    def getDropDown(self, *accountList):
        dropDown = gui.DropDownItem(width=0, height="10%")
        dropDown.style.update({"font-size": "small"})
        return dropDown

    # def dropDownChange(self, widget, *args):
    #     content_dic = load(filename="account.json")
    #     self.main_table_key = widget.get_key()
    #     self.main_table_data = content_dic[widget.get_value()]
    #     self.(refresh_content=self.main_table_data)

    @staticmethod
    def onDropDownChange(callback, *args):
        pass





    @staticmethod
    def addSubViews(*subViews, window):
        [window.append(subView) for subView in subViews]
        return window

    def isRefreshTime(self, nowTime, interValTime):
        if nowTime % interValTime == 0:
            return True
        else:
            return False



    def on_close(self):
        #Overloading on_close event to stop the Timer.

        self.stop_flag = True
        super(CWebService, self).on_close()

def createWebService(host="0.0.0.0", port=8888):
    start(CWebService, debug=True, address=host, port=port, update_interval = 1, start_browser=True, multiple_instance=True)




if __name__ == "__main__":
    dbConnPool = [CDBConnPool(log=g_log, connCount=1)]
    service = initXmlAndMysqlParam(dbConnPool, g_log)
    dbConnPool[0].init()

    g_userInfoMgr.init(db=dbConnPool[0])
    g_sysTemListMgr.init(db = dbConnPool[0])
    g_customerMgr.init(db = dbConnPool[0])
    g_productLineMgr.init(db = dbConnPool[0])



    createWebService(host=service[0], port=int(service[1]))
